//管理员

import React, {Component} from 'react';
import app from '../app';
import {Form, Input, Layout, Radio, Select, Button,Table,Modal,Row,Col, DatePicker} from 'antd';
import {requestUrl} from '../value';
import {config} from "../config";
import Star from '../components/Star';
import '../css/other.css';
import reqwest from 'reqwest';
import moment from 'moment';
import phones from '../image/photo.png';
import md5 from 'MD5';
const Option = Select.Option;
const FormItem = Form.Item;
const {Content, Header} = Layout;
const RadioGroup = Radio.Group;
const {RangePicker} = DatePicker;
const confirm = Modal.confirm;
let pageLength = 10;
const path = config.fPath;
class SiteOrder extends Component{
    constructor(props){
        super(props);
        this.state = {
            searchData: {},
            pagination: {current:1},
            data: [

            ],
            admin_type:'1',
        }
    }

    columns = [

        {
            title: '手机号码',
            dataIndex: 'order_mobile'
        },
        {
            title: '车牌号',
            dataIndex: 'car_num'
        },
        {
            title: '优惠码',
            dataIndex: 'coupon_detail_id',
            render: coupon_detail_id => {
                let text = "无";
                if (coupon_detail_id) {
                    text = "有";
                }
                return text;
            }
        },
        {
            title: '预约日期',
            dataIndex: 'order_time',
            render: order_time => {
                let text = '--';
                if(order_time){
                    text = moment(order_time).format("YYYY-MM-DD");
                }
                return text;
            }
        },
        {
            title:'预约的时间段',
            dataIndex:'order_time_detail',
        },
        {
            title: '下单时间',
            dataIndex: 'order_createtime',
            render: order_createtime => {
                let text = '--';
                if(order_createtime){
                    text = moment(order_createtime).format("YYYY-MM-DD");
                }
                return text;
            }
        },
        {
            title: '状态',
            dataIndex: 'order_status',
            render: order_status => {
                let text = "——";
                if (order_status == '1') {
                    text = "待确认";
                }else if(order_status == '2'){
                    text = "待检测";
                }else if(order_status == '3'){
                    text = "待评价";
                }else if(order_status == '4'){
                    text = "已完成";
                }else if(order_status == '5'){
                    text = "已关闭";
                }
                return text;
            }
        },

        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                        {data.order_status == 4?<Evaluation orderId={data.order_id}/>:""}
                        {data.order_status == 2?<Button  type="primary" style={{marginLeft:'10px'}}
                                                         onClick={() => this.toCheck(3,data.order_id)}>已检</Button>:""}
                        {data.order_status == 1?<Button  type="primary" style={{marginLeft:'10px'}}
                                                         onClick={() => this.toCheck(2,data.order_id)}>确定预约</Button>:""}
                        {((data.order_status == 1) || (data.order_status==2))?
                            <Button  type="danger" style={{marginLeft:'10px'}}
                                     onClick={() => this.toCheck(5,data.order_id)}>关闭</Button>:""}
                    </span>
                )
            }
        },
    ];

    formItemLayout = {
        labelCol: {span: 10},
        wrapperCol: {span: 14},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <div className="pageTitle">
                    订单管理
                </div>
                <Form layout='inline' className="login-form" onKeyDown={(e) => {
                    this.handleKeyDown(e)
                }}>
                    <FormItem label={"车牌号"} {...this.formItemLayout}>
                        {getFieldDecorator('search')(
                            <Input type="text" placeholder={"请输入车牌号/手机号"} style={{width:'180px'}}/>
                        )}

                    </FormItem>

                    <FormItem label={"预约时间"} {...this.formItemLayout}>{getFieldDecorator('bookDay')(
                        <RangePicker
                            onChange={() => {
                                setTimeout(() => {
                                    this.clickSearch()
                                }, 500);}}
                            format={'YYYY-MM-DD'}
                        />
                    )}
                    </FormItem>

                    <FormItem label={"下单时间"} {...this.formItemLayout}>{getFieldDecorator('time')(
                        <RangePicker
                            onChange={() => {
                                setTimeout(() => {
                                    this.clickSearch()
                                }, 500);}}
                            format={'YYYY-MM-DD'}
                        />
                    )}
                    </FormItem>

                    <FormItem label={"状态"} {...this.formItemLayout} style={{marginLeft:"50px"}}>
                        {getFieldDecorator('order_status')(
                            <Select onSelect={() => {
                                let _this = this;
                                setTimeout(function () {
                                    _this.clickSearch();
                                }, 500)
                            }} style={{width:'100px'}} placeholder="请选择">
                                <Option value={''}>全部</Option>
                                <Option value={'1'}>待确认</Option>
                                <Option value={'2'}>待检测</Option>
                                <Option value={'3'}>待评价</Option>
                                <Option value={'4'}>已完成</Option>
                                <Option value={'5'}>已关闭</Option>
                            </Select>
                        )}
                    </FormItem>

                    <Button type="primary" onClick={() =>this.clickSearch()} style={{marginLeft:'50px'}}>搜索</Button>

                </Form>

                <Table
                    columns={this.columns}
                    rowKey={(record, index) => index}
                    dataSource={this.state.data}
                    pagination={this.state.pagination}
                    loading={this.state.loading}
                    onChange={this.handleTableChange}
                />
            </div>
        )
    }

    componentDidMount(){
        this.fetch({});
    }

    //添加成功
    addSuccess(){
        let _this = this;
        this.fetch({
            startList: _this.state.pagination.current,
            ..._this.state.param,
        });
    }

    handleKeyDown(e) {
        if (e.keyCode == '13') {
            this.clickSearch();
        }
    }

    //点击搜索
    clickSearch(){
        this.props.form.validateFields((err, values) => {
            this.setState({searchData: values});
            const formData = app.handleTrim(values);
            if (formData) {
                this.props.form.setFieldsValue(formData);
            }
            if (values.bookDay && values.bookDay != '') {
                values.order_time_start = moment(values.bookDay[0]._d).format('YYYY-MM-DD');
                values.order_time_end = moment(values.bookDay[1]._d).format('YYYY-MM-DD');
            }
            if (values.time && values.time != '') {
                values.order_createtime_start = moment(values.time[0]._d).format('YYYY-MM-DD');
                values.order_createtime_end = moment(values.time[1]._d).format('YYYY-MM-DD');
            }
            this.fetch(values);
        })
    }

    isEmptyObject(filters) {
        for (let key in filters) {
            if (key) {
                this.setState({param: filters});
                return filters;
            }
        }
        return null;
    }

    handleTableChange = (pagination, filters, sorter) => {
        app.scrollTop();
        filters = this.isEmptyObject(filters);
        if (filters) {
            this.state.param = filters;
        }
        const pager = {...this.state.pagination};
        pager.current = pagination.current;
        this.setState({
            pagination: pager,
        });
        const searchData = this.state.searchData;
        this.fetch({
            startList: pagination.current,
            ...this.state.param,
            ...searchData,
        });
    }

    fetch = (params) => {
        let _this = this;
        _this.setState({loading: true});
        let start = 1;
        if (params.startList > 1) {
            for (let i = 1; i < params.startList; i++) {
                start += 1;
            }
        }

        reqwest({
            url: app.serverUrl + requestUrl.SEARCH_ORDER_LIST,
            method: 'post',
            data: {
                size: pageLength,
                page: start,
                site_id: app.getData('site_id'),
                ...params,
            },
            type: 'json',
        }).then((data) => {
            const pagination = {...this.state.pagination};
            if(data.code == 1){

                pagination.total = data.data.count;
                pagination.pageSize = pageLength;
                _this.setState({
                    loading: false,
                    data: data.data.dataSet || [],
                    pagination,

                });
            }else if(data.code == -1){
                app.alert('请重新登录', 'error', 3);
                window._this.props.history.push(path + '/sitelogins')
            }
            else{
                pagination.total = 1;
                _this.setState({
                    loading: false,
                    data:[],
                    pagination,
                });
            }
        });
    }

    //点击修改订单
    toCheck(e,id){
        let text;
        if(e == 2){
            text = '预约确订成功'
        }else if(e == 3){
            text = '已完成检测'
        }else if(e == 5){
            text = '关闭订单成功'
        }
        let value = {};
        let searchData = this.state.searchData;
        const _this = this;
        confirm(
            {
                content: '您确定要修改该条订单状态吗？',
                onOk() {
                    value.order_id = id;
                    value.order_status = e;
                    value.site_id = app.getData('site_id');
                    reqwest({
                        url: app.serverUrl + requestUrl.SITE_UPDATEORDER,
                        method: 'post',
                        data: {
                            ...value,
                        },
                        type: 'json',
                    }).then((req) => {
                        if (req.code == '1') {
                            app.alert(text, 'success', 2);
                            _this.fetch({
                                startList: _this.state.pagination.current,
                                ...searchData,
                                ..._this.state.param
                            });
                        } else if (req.code == '2') {
                            app.alert(req.msg, 'success', 2);
                        }
                    })
                },
                onCancel() {
                },
            });
    }
}





//查看评价
class Evaluation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            evaluate:{},
            serverStar:'5',
            effectStar:'5',
        }
    }

    render() {
        return (
            <span>
                <Button type="primary" onClick={() => this.showModal(true,this.props.orderId)}
                        style={{marginLeft:'10px'}}>查看评价</Button>
                <Modal
                    visible={this.state.visible}
                    title="查看车辆详情"
                    onCancel={() => this.showModal(false)}
                    footer={[
                        <Button key="back" onClick={() => this.showModal(false)}>关闭</Button>
                    ]}
                >
                    <Row className="detailList">
                        <Col span={5} offset={4}>服务评分:</Col>
                        <Col span={15}>
                            <Star point={this.state.evaluate.evaluate_attitude}/>
                        </Col>
                    </Row>
                    <Row className="detailList">
                        <Col span={5} offset={4}>效率评分:</Col>
                        <Col span={15}>
                            <Star point={this.state.evaluate.evaluate_effective}/>
                        </Col>
                    </Row>
                    <Row className="detailList">
                        <Col span={5} offset={4}>内容:</Col>
                        <Col span={15}>
                            {this.state.evaluate.evaluate_text}
                        </Col>
                    </Row>
                </Modal>
            </span>
        )
    }

    //弹出与取消
    showModal(show,id) {
        if (show) {
            let evaluate = {};
            let value = {};
            let _this = this;
            value.order_id = id;
            reqwest({
                url: app.serverUrl + requestUrl.SEARCH_ORDEREVALUATE,
                method: 'post',
                data: {
                    order_id: id,
                },
                type: 'json',
            }).then((req) => {
                if (req.code == 1) {
                    if (!req.data.evaluate_text) req.data.evaluate_text = '暂无评价';
                    evaluate = req.data
                } else {
                    app.alert(req.msg, 'success', 2)
                }
                _this.setState({evaluate});
            })
        }
        this.setState({visible: show});
    }

}

const SiteOrders = Form.create()(SiteOrder);

export default SiteOrders


